﻿using System;
using System.Drawing;
using System.Text.RegularExpressions;
using com.fukefu.source;
using com.fukefu.sql;

namespace com.fukefu.info.blog
{
    public class SinaBlog : Information
    {
        private string uid;
        private string vtoken;

        private CookieFactory cf = CookieFactory.GetInstance();
        public event MyDelegate1 _dispaly;

        private SqlServerOperate sql = new SqlServerOperate();
        //注册
        public bool Register(string name, string pass)
        {
            cf.Clear("http://blog.sina.com.cn");
            string html = source.Get("https://login.sina.com.cn/signup/signup.php?entry=blog&src=blog&srcuid=&r=", "https://login.sina.com.cn/signup/signupmail.php?en");
            MatchCollection mc = Regex.Matches(html, "<input type=\"hidden\" name=\"([^\"]+)\" value=\"([^\"]*)\">");

            ParametersData pd = new ParametersData("gb2312");
            foreach (Match m in mc)
            {
                GroupCollection gc = m.Groups;
                pd.Add(gc[1].Value, gc[2].Value);
            }
            pd.Add("user_name", name);
            pd.Add("password", pass);
            pd.Add("password2", pass);
            pd.Add("otherQid", "");
            pd.Add("pwdA", name);
            pd.Add("nick", name);
            pd.Add("after", "on");
            pd.Add("selectQid", "我儿时居住地的地址？");
            pd.Add("door", InputBox.ShowInputBox("https://login.sina.com.cn/cgi/pin.php?r=" + random.Next(100000000)));

            if (!CheckUserName(name))
            {
                return false;
            }
            html = source.Post("https://login.sina.com.cn/signup/signup1.php?entry=blog&src=blog&srcuid=", pd.Read(), "https://login.sina.com.cn/signup/signup.php?entry=blog&src=blog&srcuid=&r=");
            if (html.IndexOf("<p class=\"title_note red\">") != -1)
            {
                Display(Regex.Match(html, "<p class=\"title_note red\">([^<]+)</p>").Groups[1].Value);
                return false;
            }
            string url = Regex.Match(html, "location.replace\\(\"([^\"]+)\"\\);").Groups[1].Value;
            html = source.Get(url);
            url = Regex.Match(html, "location.replace\\('([^\']+)'\\);").Groups[1].Value;
            html = source.Get(url);
            //跳转到准备开通
            html = source.Get("http://control.blog.sina.com.cn/reg/reg_blog_module.php?src=&version=7", url);
            //开通blog
            html = source.Post("http://control.blog.sina.com.cn/riaapi/reg/open_blog_simple.php?domain=1", "src=blogicp&srcuid=", "http://control.blog.sina.com.cn/reg/reg_blog_succ.php?srcuid=&version=7&src=blogicp");
            if (html.IndexOf("code\":\"A00006\",\"data\"") == -1)
            {
                Display("博客开通失败(" + Regex.Match(html, "code\":\"([^\"]+)\",\"data\"").Groups[1].Value + ")");
                return false;
            }
            //跳转到设置模板
            html = source.Post("http://control.blog.sina.com.cn/riaapi/reg/init_blog_module.php", "module=YTo0OntpOjA7YTo4OntzOjQ6InR5cGUiO3M6MToiMyI7czozOiJ1cmwiO3M6Njc6Imh0dHA6Ly9zaW1nLnNpbmFqcy5jbi9ibG9nN3N0eWxlL2ltYWdlcy9icmluZy9za2luL2NoaWxkL2JhYnkxMS5qcGciO3M6NToic3R5bGUiO3M6MToiMyI7czo5OiJzdHlsZV9jc3MiO3M6MzoiN18yIjtzOjI6ImMxIjtzOjE3OiI5MDEsMTAwMDQsMywxMiw2MyI7czoyOiJjMiI7czo1OiIxMDAwMSI7czoyOiJjMyI7czo2OiI4NiwxLDIiO3M6NDoic2hvdyI7czoxMjoi5aSn5pa5566A5rSBIjt9aToxO2E6Nzp7czo0OiJ0eXBlIjtzOjE6IjQiO3M6MzoidXJsIjtzOjY1OiJodHRwOi8vc2ltZy5zaW5hanMuY24vYmxvZzdzdHlsZS9pbWFnZXMvYnJpbmcvc2tpbi9zaG93L3BpYzIwLmpwZyI7czo1OiJzdHlsZSI7czoxOiIxIjtzOjk6InN0eWxlX2NzcyI7czozOiI1XzkiO3M6MjoiYzEiO3M6MTU6IjkwMSwxMDAwNCwxMiw2MyI7czoyOiJjMiI7czo4OiI4NiwzLDEsMiI7czoyOiJjMyI7czo1OiIxMDAwMSI7fWk6MjthOjY6e3M6NDoidHlwZSI7czoxOiI1IjtzOjM6InVybCI7czo2MToiaHR0cDovL3NpbWcuc2luYWpzLmNuL2Jsb2c3c3R5bGUvaW1hZ2VzL2JyaW5nL3NraW4vbWluZC8yLmpwZyI7czo1OiJzdHlsZSI7czoxOiIxIjtzOjk6InN0eWxlX2NzcyI7czo0OiIyXzIzIjtzOjI6ImMxIjtzOjIxOiI5MDEsMyw4LDEsMiwxMiw2MywxMTMiO3M6MjoiYzIiO3M6NToiMTAwMDEiO31pOjM7YTo2OntzOjQ6InR5cGUiO3M6MToiNiI7czozOiJ1cmwiO3M6NjY6Imh0dHA6Ly9zaW1nLnNpbmFqcy5jbi9ibG9nN3N0eWxlL2ltYWdlcy9icmluZy9za2luL2NvbG9yZnVsLzEwLmpwZyI7czo1OiJzdHlsZSI7czoxOiIxIjtzOjk6InN0eWxlX2NzcyI7czo0OiIzMF8yIjtzOjI6ImMxIjtzOjIzOiI5MDEsMTAwMDQsOCwzLDEsMiwxMiw2MyI7czoyOiJjMiI7czo1OiIxMDAwMSI7fX0%3D&module_checked=0&backdefault=0&version=7", "http://control.blog.sina.com.cn/reg/reg_blog_module.php?src=&version=7");
            if (html.IndexOf("code\":\"A00006\",\"data\"") != -1)
            {
                Display("模板选择成功");
            }
            else
            {
                Display("模板选择失败");
                return false;
            }
            //添加好友
            html = source.Get("http://control.blog.sina.com.cn/reg/reg_blog_attention.php?src=1&version=7", "http://control.blog.sina.com.cn/reg/reg_blog_attention.php?src=1&version=7");
            uid = Regex.Match(html, "uid : \"([0-9]+)\"").Groups[1].Value;
            string p = "";
            mc = Regex.Matches(html, "href=\"http://blog.sina.com.cn/u/([0-9]+)\" title=");
            foreach (Match m in mc)
            {
                GroupCollection gc = m.Groups;
                p += (p.Equals("") ? "" : "%2C") + gc[1].Value;
            }
            html = source.Get("http://control.blog.sina.com.cn/riaapi/reg/attention_add_batch.php?uid=" + uid + "&aids=" + p + "&version=7&varname=requestId_5" + random.Next(10000000), "http://control.blog.sina.com.cn/reg/reg_blog_attention.php?src=1&version=7");
            if (html.IndexOf("code\":\"A00006\",\"data\"") != -1)
            {
                Display("好友添加成功");
            }
            else
            {
                Display("好友添加失败");
                return false;
            }
            html = source.Get("http://control.blog.sina.com.cn/reg/reg_blog_init.php?version=7", "http://control.blog.sina.com.cn/reg/reg_blog_attention.php?src=1&version=7");
            if (html.IndexOf("恭喜您，博客快速设置已完成") != -1)
            {
                sql.Update("insert into 全局设置.dbo.[_sina_新浪账号](name,password,uid) values('" + name + "@sina.cn','" + pass + "'," + uid + ")");
                Display("恭喜您，博客快速设置已完成");
                html = source.Get("http://control.blog.sina.com.cn/admin/article/article_add.php?index");
                vtoken = Regex.Match(html, "name=\"vtoken\" value=\"([^\"]+)\"").Groups[1].Value as string;
                return true;
            }
            Display("博客开通失败");
            return false;
        }
        //检查用户名是否被使用
        private bool CheckUserName(string name)
        {
            string html = source.Post("https://login.sina.com.cn/signup/check_user.php?t=" + MyFunction.GetTimestampNow(), "application/x-www-form-urlencoded; charset=UTF-8", MyFunction.StringtoByte("from=cnmail&name=" + name), "https://login.sina.com.cn/signup/signup1.php?entry=blog&src=blog&srcuid");
            if (html.Equals("yes"))
            {
                Display(name + " 用户名被占用");
                return false;
            }
            return true;
        }
        //登陆
        public override bool Login(string name, string pass, string vcode)
        {
            string html = source.Get("http://login.sina.com.cn/sso/prelogin.php?entry=boke&callback=sinaSSOController.preloginCallBack&su=JUU1JThGJTkxJUU1JTg4JUIw&client=ssologin.js%28v1.3.17%29&_=" + MyFunction.GetTimestampNow(), "http://blog.sina.com.cn");
            string servertime = Regex.Match(html, "\"servertime\":([0-9]+),").Groups[1].Value;
            string nonce = Regex.Match(html, "nonce\":\"([^\"]+)\"").Groups[1].Value;

            ParametersData pd = new ParametersData();
            pd.Add("entry", "boke");
            pd.Add("gateway", "1");
            pd.Add("from", "");
            pd.Add("savestate", "30");
            pd.Add("useticket", "0");
            pd.Add("su", MyFunction.Base64Code(name));
            pd.Add("service", "sso");
            pd.Add("servertime", servertime);
            pd.Add("nonce", nonce);
            pd.Add("pwencode", "wsse");
            pd.Add("sp", MyFunction.HashCode(MyFunction.HashCode(MyFunction.HashCode(pass)) + servertime + nonce));
            pd.Add("encoding", "UTF-8");
            pd.Add("callback", "parent.sinaSSOController.loginCallBack");
            pd.Add("returntype", "IFRAME");
            pd.Add("setdomain", "1");
            pd.Add("door", InputBox.ShowInputBox("https://login.sina.com.cn/cgi/pin.php?r=" + random.Next(100000000)));

            html = source.Post("http://login.sina.com.cn/sso/login.php?client=ssologin.js(v1.3.11)", pd.Read(), "http://blog.sina.com.cn");
            Match m = Regex.Match(html, "retcode\":0,\"uid\":\"([0-9]+)\"");
            if (m.Length == 0)
            {
                return false;
            }
            else
            {
                uid = m.Groups[1].Value as string;
                html = source.Get("http://control.blog.sina.com.cn/admin/article/article_add.php?index");
                vtoken = Regex.Match(html, "name=\"vtoken\" value=\"([^\"]+)\"").Groups[1].Value as string;
                return true;
            }
        }
        //发布
        public bool Post(string title, string content, string tag)
        {
            ParametersData pd = new ParametersData();
            pd.Add("ptype", "");
            pd.Add("teams", "");
            pd.Add("worldcuptags", "");
            pd.Add("album", "");
            pd.Add("album_cite", "");
            pd.Add("blog_id", "");
            pd.Add("is_album", "0");
            pd.Add("stag", "");
            pd.Add("sno", "");
            pd.Add("book_worksid", "");
            pd.Add("channel_id", "");
            pd.Add("baidu_url", "");
            pd.Add("channel", "");
            pd.Add("newsid", "");
            pd.Add("fromuid", "");
            pd.Add("wid", "");
            pd.Add("articletj", "");
            pd.Add("vtoken", vtoken);
            pd.Add("is_media", "0");
            pd.Add("is_stock", "0");
            pd.Add("is_tpl", "0");
            pd.Add("assoc_article", "");
            pd.Add("assoc_style", "1");
            pd.Add("assoc_article_data", "");
            pd.Add("article_BGM", "");
            pd.Add("xRankStatus", "");
            pd.Add("commentGlobalSwitch", "");
            pd.Add("commenthideGlobalSwitch", "");
            pd.Add("articleStatus_preview", "1");
            pd.Add("source", "");
            pd.Add("topic_id", "0");
            pd.Add("topic_channel", "0");
            pd.Add("topic_more", "");
            pd.Add("utf8", "1");
            pd.Add("date_pub", "");
            pd.Add("blog_title", title);
            pd.Add("time", "");
            pd.Add("blog_body", content);
            pd.Add("blog_class", "00");
            pd.Add("tag", tag);
            pd.Add("x_cms_flag", "0");
            pd.Add("sina_sort_id", "117");
            pd.Add("join_circle", "1");
            string html = source.Post("http://control.blog.sina.com.cn/admin/article/article_post.php", pd.Read(), "http://control.blog.sina.com.cn/admin/article/article_add.php");
            if (Regex.IsMatch(html, "B06001"))
            {
                //发布网址写入数据库
                sql.Update("insert into 全局设置.dbo.[_sina_新浪网址](url,tag,cont,uid) values('http://blog.sina.com.cn/s/blog_" + Regex.Match(html, "\"code\":\"B06001\",\"data\":\"([^\"]+)\"").Groups[1].Value + ".html','" + tag + "','" + content.Replace("'", "") + "','" + uid + "')");
                return true;
            }
            return false;
        }
        //添加分类
        public bool AddType(string typeName)
        {
            string html = source.Get("http://blogcnf.sinajs.cn/acate?jv=x&" + uid);
            string typeId = "", name = "";
            MatchCollection mc = Regex.Matches(html, "{\"id\":([0-9]+),\"name\":\"([^\"]+)\"}");
            GroupCollection gc;
            string midName;
            foreach (Match m in mc)
            {
                gc = m.Groups;
                midName = MyFunction.Uncode(gc[2].Value as string);
                //判断增加的分类是不是存在
                if (midName.Equals(typeName))
                {
                    return false;
                }
                typeId += (typeId.Equals("") ? "" : "|") + gc[1].Value;
                name += (name.Equals("") ? "" : "|") + midName;
            }
            typeId += (typeId.Equals("") ? "" : "|") + "-1";
            name += (name.Equals("") ? "" : "|") + typeName;
            return Regex.IsMatch(source.Post("http://control.blog.sina.com.cn/admin/article/article_class_save2.php?uid=" + uid + "&r=0.03102259543963448&domain=1", "typename=" + name + "&number=" + typeId), "A00006");
        }
        //删除分类
        public void deleteType(string typeName)
        {
            string html = source.Get("http://blogcnf.sinajs.cn/acate?jv=x&" + uid);
            string typeId = "", name = "";
            MatchCollection mc = Regex.Matches(html, "{\"id\":([0-9]+),\"name\":\"([^\"]+)\"}");
            GroupCollection gc;
            string midName;
            foreach (Match m in mc)
            {
                gc = m.Groups;
                midName = MyFunction.Uncode(gc[2].Value as string);
                if (!midName.Equals(typeName))
                {
                    typeId += (typeId.Equals("") ? "" : "|") + gc[1].Value;
                    name += (name.Equals("") ? "" : "|") + midName;
                }
            }
            source.Post("http://control.blog.sina.com.cn/admin/article/article_class_save2.php?uid=" + uid + "&r=0.03102259543963448&domain=1", "typename=" + name + "&number=" + typeId);
        }
        //删除所有分类
        public void deleteAllType()
        {
            source.Post("http://control.blog.sina.com.cn/admin/article/article_class_save2.php?uid=" + uid + "&r=0.03102259543963448&domain=1", "typename=&number=");
        }
        //修改title名字
        public bool updateBlogTitle(string name)
        {
            string html = source.Get("http://blog.sina.com.cn/u/" + uid);
            string encrypt_code = Regex.Match(html, "encrypt_code = \"([^\"]+)\"").Groups[1].Value as string;
            html = source.Get("http://control.blog.sina.com.cn/admin/custom/update_blogtitle.php?uid=" + uid + "&Title=" + MyFunction.EncodeByUtf8(name) + "&secure_code=" + encrypt_code + "&varname=requestId_91345881");
            return Regex.IsMatch(html, "A00006");
        }
        //收藏文章
        public bool addFavourite(string titleId)
        {
            return Regex.IsMatch(source.Get("http://control.blog.sina.com.cn/admin/article/favourites_save.php?blog_id=" + titleId + "&uid=" + uid + "&varname=requestId_42960688"), "A00006");
        }
        //删除文章
        public bool deleteArticle(string titieId)
        {
            return Regex.IsMatch(source.Get("http://control.blog.sina.com.cn/admin/article/article_del_recycle.php?blog_id[]=" + titieId + "&uid=" + uid + "&varname=requestId_42960688"), "A00006");
        }
        //删除文章onePage
        public void deleteArticleByIndex()
        {
            string html = source.Get("http://blog.sina.com.cn/u/" + uid);
            MatchCollection mc = Regex.Matches(html, "id=\"d_10001_([^\"]+)\"[^>]+>\\[<cite>删除</cite>");
            GroupCollection gc;
            foreach (Match m in mc)
            {
                gc = m.Groups;
                deleteArticle(gc[1].Value);
            }
        }
        //显示信息
        private void Display(string str)
        {
            if (_dispaly != null)
            {
                _dispaly(str);
            }
        }

        public override Image GetFlushCodeImage()
        {
            return source.GetImage("https://login.sina.com.cn/cgi/pin.php?r=" + random.Next(100000000));
        }

        public override InformationResult PostArticle(string title, string content, string vcode)
        {
            throw new NotImplementedException();
        }
    }
}
